package com.axjy.controller;

import com.alibaba.fastjson.JSON;
import com.axjy.pojo.Role;
import com.axjy.pojo.User;
import com.axjy.service.RoleService;
import com.axjy.util.Log;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/sys/role")
public class RoleController {

    private String msg;

    @Resource
    private RoleService roleService;

   /* @GetMapping("/list")
    public ModelAndView index(){
        ModelAndView mav=new ModelAndView("list");
        return mav;
    }
*/
    @GetMapping(value="/search")
    /**
     * 该主机会把返回值放入PrintWriter中,
     * 使用responseBody必须配置转化器HttpMessageConverter
     * 返回字符串时，默认采用的是StringHttpMessageConverter
     */
    public  List<Role> search(){
        List<Role> list=roleService.search();
       // String json= JSON.toJSONString(list);//该行代码也可以采用全局方式解决
        return list;
    }

    @PostMapping("/update")
    public String update(Role role,HttpSession session){
        User loginUser= (User) session.getAttribute("loginUser");
        if(loginUser!=null) {
            role.setModifyBy(loginUser.getUsername());
        }
        role.setModifyTime(new Date());
        try{
            roleService.update(role);
            msg="修改角色成功！";
        }catch (Exception ex){
            msg="修改角色失败！";
            Log.LOGGER.error(msg,ex);
        }
        return msg;
    }

    @GetMapping("/del")
    public String del(Integer id){
        try{
            roleService.del(id);
            msg="删除用户成功！";
        }catch (Exception ex){
            msg="删除用户失败！请检查该角色下是否拥有员工信息！";
            Log.LOGGER.error(msg,ex);
        }
        return msg;
    }

}
